import pandas as pd
from tkinter import Tk
from tkinter.filedialog import askopenfilename

# # 创建一个隐藏的Tk窗口
# Tk().withdraw()
#
# # 打开文件选择对话框
# file_path = askopenfilename(title="选择CSV文件", filetypes=[("CSV files", "*.csv")])
#
# # 读取CSV文件
# data = pd.read_csv(file_path)
#
# # 初始化结果
# groups = []
# current_group_SDI = []
# current_group_SDO = []

def extract_spi():
    # 创建一个隐藏的Tk窗口
    Tk().withdraw()
    # 打开文件选择对话框
    file_path = askopenfilename(title="选择CSV文件", filetypes=[("CSV files", "*.csv")])
    if not file_path:
        messagebox.showwarning("警告", "未选择文件！")
        return

        # 读取CSV文件
    data = pd.read_csv(file_path)
    # 初始化结果
    current_group_sdi = []
    current_group_sdo = []
    groups = []

    # 遍历每一行数据
    for index, row in data.iterrows():
        status = row.iloc[0].strip('="')  # 使用iloc来获取第二列（Status(8 bits data)）
        cleaned_row = [item.strip('=" ') for item in row.iloc[1:17]]  # 清洗D0到D15的内容
        cleaned_row = [f"0x{item}" for item in cleaned_row if item]  # 去除空项例如""
        print(status)
        if status == 'Idle':
            if current_group_sdi:
                groups.append(current_group_sdi)
                current_group_SDI = []

            if current_group_sdo:
                groups.append(current_group_sdo)
                current_group_sdo = []
        else:
            # 将SDI和SDO的数据提取到当前组
            if status == 'SDI':
                for d_data in cleaned_row:
                    current_group_sdi.append(d_data)  # 提取D0到D15的内容
                print(current_group_sdi)
            if status == 'SDO':
                for d_data in cleaned_row:
                    current_group_sdo.append(d_data)  # 提取D0到D15的内容
                print(current_group_sdo)
    # 添加最后一个组（如果存在）
    if current_group_sdi:
        groups.append(current_group_sdi)
    if current_group_sdo:
        groups.append(current_group_sdo)

        # 输出结果到output_textbox
    output_textbox.delete(1.0, tk.END)  # 清空之前的内容
    output_textbox.insert(tk.END, "Cleaned SDI Group:\n")
    output_textbox.insert(tk.END, "\n".join(current_group_SDI) + "\n\n")
    output_textbox.insert(tk.END, "Cleaned SDO Group:\n")
    output_textbox.insert(tk.END, "\n".join(current_group_SDO))
    # # 清洗提取的数组
    # cleaned_groups = []
    # for group in groups:
    #     cleaned_group = []
    #     for entry in group:
    #         cleaned_entry = [item.strip('="') for item in entry]  # 去掉等号和引号
    #         cleaned_group.append(cleaned_entry)
    #     cleaned_groups.append(cleaned_group)
    #
    # # 输出结果
    # for i, group in enumerate(groups):
    #     print(f"Cleaned Group {i + 1}: ")
    #     # for entry in group:
    # print(group)